<template>
  <div class="bbq-collapse-item">
    <div class="bbq-header">
      <slot name="title"></slot>
      <div class="bbq-header-action" :class="{'is-open':modelValue}" @click="triggerChange">
        <slot name="action"></slot>
      </div>
    </div>
    <transition v-on="on" name="trans">
      <div v-show="modelValue" class="bbq-content">
        <slot name="content"></slot>
      </div>
    </transition>
  </div>
</template>

<script lang="ts">
import {defineComponent} from 'vue'
export default defineComponent({
  name: "bbq-collapse-item",
  props:{
    modelValue:{
      type: Boolean,
      default: false
    }
  },
  emits:['update:modelValue'],
  setup(props,ctx){
    const on = {
      beforeEnter(el: HTMLElement){
        //进入之前，
        el.style.height = '0'
      },
      enter(el: HTMLElement) {
        el.style.height = el.scrollHeight + 'px'
      },
      afterEnter(el: HTMLElement){
        el.style.height = ''
      },
      beforeLeave(el: HTMLElement){
        el.style.height = el.scrollHeight + 'px'
      },
      leave(el: HTMLElement){
        //神奇的if 没有经过if进行一次计算的话，style的设置会重在一起导致动画失效，所以通过if计算错开顺序
        if (el.scrollHeight !== 0) {
          //在vue3中会出现 transitionProperty ： none的样式，需要手动设置一下
          el.style.transitionProperty = 'height'
          el.style.height = '0'
        }
      },
      afterLeave(el: HTMLElement){
        el.style.height = ''
      }
    }
    const triggerChange =()=>{
      ctx.emit('update:modelValue',!props.modelValue)
    }

    return {
      on,
      triggerChange
    }
  }
})
</script>